package com.example.service.impl;

import com.example.entity.Result;
import com.example.service.UploadImgService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author:tjf
 * @Description:
 */
@Service
public class UploadImgServiceImpl implements UploadImgService {
    @Value("${file.upload-path}")
    private String fileUploadPath ;
    /**
     * 保存用户上传的商品图片的业务方法
     * @param multipartFile
     * @return
     */
    @Override
    public Result saveUploadProductImg(MultipartFile multipartFile) {
        try {

            // 获取保存 上传的文件 的目录 的文件对象
            File uploadDirFile = ResourceUtils.getFile(fileUploadPath);
            // 获取目录文件对象的磁盘路径
            String absolutePath = uploadDirFile.getAbsolutePath();
            // 指定上传文件的保存路径
            String saveUploadFilePath = absolutePath + "\\" + multipartFile.getOriginalFilename();
            // 保存图片
            multipartFile.transferTo(new File(saveUploadFilePath));
            // 响应结果
            return Result.ok("文件上传成功！");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }
    }
}
